<template>
	<div>
		<el-form :disabled="isDisabled" class="dialog-layout" ref="userForm" :rules="rules" :model="state.ruleForm" size="default" label-width="100px">
			<el-row :gutter="35">
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
					<el-form-item label="OTP码长度" prop="digits">
						<el-input v-model="state.ruleForm.digits" placeholder="请输入OTP码长度" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
					<el-form-item label="更新时间" prop="period">
						<el-input v-model="state.ruleForm.period" placeholder="请输入更新时间" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
					<el-form-item label="PREVIOUS" prop="previous">
						<el-input v-model="state.ruleForm.previous" placeholder="请输入PREVIOUS" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
					<el-form-item label="FUTURE" prop="future">
						<el-input v-model="state.ruleForm.future" placeholder="请输入FUTURE" clearable></el-input>
					</el-form-item>
				</el-col>

				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
					<el-form-item label="secretKey">
						<el-input disabled v-model="state.initItem.secretKey"></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
					<el-form-item label="URI">
						<el-input disabled v-model="state.initItem.uri" type="textarea" rows="3"></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
					<el-form-item label="二维码">
						<el-image :src="state.initItem.qrCode" fit="cover">
							<template #error>
								<div class="image-slot">暂无设置TOTP</div>
							</template>
						</el-image>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<div class="dialog-btn">
			<el-button @click="onCancel" size="default">取 消</el-button>
			<el-button @click="delBtn" :disabled="state.isDetails" type="danger" size="default">清除TOTP</el-button>
			<el-button :disabled="isDisabled" type="primary" @click="onSubmit(userForm)" size="default">确 认</el-button>
		</div>
	</div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { CreateSecret, GetSysUserTotpConfig, ClearSecret, TotpGenerate } from '/@/api/user/index';

import { FormInstance, ElMessage, ElMessageBox } from 'element-plus';
// 定义父组件传过来的值
const props = defineProps({
	editItem: {
		type: Object,
		default: () => {},
	},
	isDisabled: {
		type: Boolean,
		default: false,
	},
});
// 定义子组件向父组件传值/事件
const emit = defineEmits(['close']);

// 定义变量内容
const state = reactive({
	ruleForm: {
		digits: null, // OTP 码长度。默认6位。
		period: null, // OTP 算法的时钟周期。单位：秒。
		previous: null, // 验证码过期
		future: null, // 验证码过期
		sysUserId: props.editItem.id,
	} as any,
	initItem: {
		secretKey: '',
		uri: '',
		qrCode: '',
	} as any,
	isDetails: true,
});
onMounted(() => {
	getTableData();
});
// 初始化列表
const getTableData = async () => {
	let data = await GetSysUserTotpConfig(props.editItem.id);
	if (data.data) {
		state.isDetails = false;
		state.initItem = data.data;
		for (const key in state.ruleForm) {
			if (state.initItem[key]) state.ruleForm[key] = state.initItem[key];
		}
		if (state.initItem.qrCode) {
			state.initItem.qrCode = `data:image/png;base64,${state.initItem.qrCode}`;
		}
	}
};

// 关闭弹窗
const onCancel = () => {
	emit('close');
};

const rules = reactive({
	digits: [{ pattern: /^[1-9]\d*$/, message: '请输入合法OTP码长度', trigger: ['blur', 'change'] }],
	period: [{ pattern: /^[1-9]\d*$/, message: '请输入更新时间', trigger: ['blur', 'change'] }],
	previous: [{ pattern: /^[1-9]\d*$/, message: '请输入合法PREVIOUS', trigger: ['blur', 'change'] }],
	future: [{ pattern: /^[1-9]\d*$/, message: '请输入合法FUTURE', trigger: ['blur', 'change'] }],
});
const userForm = ref<FormInstance>();
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			const params = {
				...state.ruleForm,
			};

			await CreateSecret(params);
			ElMessage.success(props.editItem ? '修改成功' : '新增成功');
			onCancel();
		}
	});
};
// 删除账户
const delBtn = () => {
	ElMessageBox.confirm(`此操作将永久删除系统用户的 Totp Secret，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		await ClearSecret(props.editItem.id);
		ElMessage.success('删除成功');
		onCancel();
	});
};
</script>
